import React from "react";
import type { EventHandler, PropsWithChildren, ReactElement } from "react";

import copy from "copy-to-clipboard";

interface CopyToClipboardProps {
  text: string;
  onCopy?: (text: string, result: boolean) => void;
  children: ReactElement;
  options?: {
    debug?: boolean;
    message?: string;
    format?: string;
  };
}

const CopyToClipboard = (props: CopyToClipboardProps) => {
  const { text, onCopy, children, options } = props;
  const onClick = (event: React.MouseEvent<HTMLElement, MouseEvent>) => {
    const result = copy(text, options);
    if (onCopy) {
      onCopy(text, result);
    }

    // 安全地访问子元素的 onClick 属性
    const childProps = children.props as {
      onClick?: React.MouseEventHandler<HTMLElement>;
    };
    if (typeof childProps.onClick === "function") {
      childProps.onClick(event);
    }
  };

  return React.cloneElement(children, { onClick } as any);
};

export default CopyToClipboard;
